/**
 * Created by xiewei on 15/八月/13.
 * 寄养家庭详情
 */
var ffId = getUrlParam('ffId');;
var banFlag = false;
var doc = document;
var stop = null;
//寄养家庭信息参数
var familyReqData = {
    ffId: ffId,
    jd: '',
    wd: ''
}
var imgDir = 'img/';
/**
 * 查看大图
 * @param imgList
 * @param i
 */
function showImg(imgList,i){
    stop = doc.documentElement.scrollTop == 0 ? doc.body.scrollTop : doc.documentElement.scrollTop;
    var width = getPageWidth();
    var height = getPageHeight();
    //显示遮罩
    $("#img_slide_cover").css({
        "height": height
    }).removeClass("hidden").animate({
        opacity: "1"
    },300);
    //拼图片展示相关节点
    var slides = $("#slides");
    height = height-50;
    imgList.each(function(){
        var img = $("<img>").attr("src",$(this).attr("bigsrc")).hide();
        var imgTimer = setInterval(function(){
            if(img[0].complete){
                clearInterval(imgTimer);
                //图片定位
                if(img[0].height/img[0].width > height/width){
                    var imgWidth = height/img[0].height*img[0].width;
                    img.css({
                        height: height,
                        width: imgWidth,
                        marginLeft: width/2-imgWidth/2
                    });
                }else{
                    var imgHeight = width/img[0].width*img[0].height;
                    img.css({
                        width: width,
                        height: imgHeight,
                        top : height/2-imgHeight/2
                    });
                }
            }
        },10);
        slides.append(img);
    });
    slides.slidesjs({
        heigth: height,
        start: i,
        navigation: false
    });
    slides.css("margin-top","25px");
    stopScroll();
}
/**
 * 禁止页面滚动
 */
var stopScroll = function(){
    banFlag = true;
    $("#img_slide_cover")[0].scrollTop = "0px";
    document.getElementById("img_slide_cover").scrollTop = "0px";
    document.documentElement.style.overflow = "hidden";
    document.body.style.overflow = "hidden";
    document.addEventListener("touchmove",function(e){
        if(banFlag){
            e.preventDefault;
            e.returnValue = false;
            e.stopPropagation();
            return false;
        }
    });
}
/**
 * 恢复页面滚动
 */
var restartScroll = function(){
    document.documentElement.scrollTop = stop;
    document.body.scrollTop = stop;
    document.documentElement.style.overflowY = "auto";
    document.body.style.overflowY = "auto";
    banFlag = false;
}
/**
 * 查看大图设置
 */
var checkBigImg = function(){
    stopScroll();
    //不点击的展示
    var imgList = $(".top_pic_list span:not(.video)");
    var width = getPageWidth();
    if(imgList.length>1){
        $('#topFmlPhotos').normalslidesjs({
            width: width,
            height: width*0.7,
            navigation: false,
            play:{
                active: true,
                auto: false
            }
        });
    }
    //点击后展示大图
    if(imgList.length>0) {
        $.each(imgList,function(i){
            $(this).css({
                height: width*0.7
            });
            $(this).bind("click",function(){
                showImg(imgList,i+1);
            });
        });
        $("#slides").click(function(){
            //关闭
            $("#img_slide_cover").animate({
                opacity: "0"
            },300);
            setTimeout("$('#img_slide_cover').addClass('hidden')",200);
            setTimeout("$('#slides').empty()",300);
            restartScroll();
        });
    }
    restartScroll();
}
/**
 * 评价等级对应的分数
 * @param grade
 * @param starDiv
 */
var crtGrdStrt = function(grade,starDiv){
    var all = Math.floor(grade);//整颗个数
    var empty = 5-all;
    for(var i = 0; i < all; i ++){
        $('<img>').attr('src','img/'+gradeStars.all).appendTo(starDiv);
    }
    if(grade-all > 0){//半颗
        empty--;
        $('<img>').attr('src','img/'+gradeStars.half).appendTo(starDiv);
    }
    for(var i = 0; i < empty; i ++){
        $('<img>').attr('src','img/'+gradeStars.empty).appendTo(starDiv);
    }
}
/**
 * 服务列表节点拼接
 */
var crtSrvrLst = function(servers,ul){
    for(var i = 0; i < servers.length; i ++){
        var server = servers[i];
        var img = $('<img>');
        if(server.icon){
            img.attr('src',server.icon)
        }else{
            img.attr('src','img/'+serveImgMap[server.fsId]);
        }
        var integral = server.price.split('.')[0];
        var decimal = server.price.split('.')[1];
        var right = $('<div>').addClass('right');
        $('<p>').html(server.content).appendTo(right);
        $('<span>').addClass('price').html('&yen;<b>'+integral+'</b>.'+decimal).appendTo(right);
        $('<li>').append(img,right).appendTo(ul);
    }
}
/**
 * 获取寄养家庭信息
 */
var getFamilyInfo = function(){
    //获取寄养家庭信息
    $.ajax({
        url: '/dog2/appFamily/getFamilyInfo',
        dataType: 'json',
        type: 'POST',
        data: paramCoding(familyReqData),
        success: function(res){
            if(res.respCode == 0){
                //展示家庭基础信息
                $('#fmlHeader').removeClass('hidden');
                //是否暂不接单
                if(res.enable!=1){
                    $('#familyUnable').text(res.unableReason);
                    $('#familyUnable').removeClass('hidden');
                }
                //头部轮播视频\图片
                var photoDiv = $('#topFmlPhotos');
                photoDiv.find('span').remove();
                //视频
                if(res.media){
                    var width = getPageWidth();
                    var W = width;
                    var H = W*0.7;
                    if(res.coverScale > 0.7){
                        W = H/res.coverScale;
                    }else{
                        H = W*res.coverScale;
                    }
                    var video = $('<video>').attr('src',res.media)
                        .attr('poster',res.cover+imgSize.thumbnail)
                        .attr('preload','auto')
                        .addClass('stop');
                    $('<p>').text('您的浏览器不支持播放该视频:(').appendTo(video);
                    var imgW = width*0.2;
                    var img = $('<img>').attr('src',imgDir+'button_album_video_play.png')
                        .css({marginTop: H/2-imgW/2});
                    var span = $('<span>').addClass('video')
                        .css({
                            background: '#000 url('+res.cover+imgSize.thumbnail+') no-repeat center center',
                            backgroundSize: W+'px '+H+'px'
                        });
                    video.appendTo(span);
                    img.appendTo(span);
                    span.appendTo(photoDiv);
                    //点击播放\暂停
                    span.on('click',function(e){
                        if(video.hasClass('stop')){
                            video.css({
                                width: W,
                                height: H,
                                marginTop: width*0.7/2-H/2
                            });
                            video.next().css({
                                marginLeft: '-'+(W/2+imgW/2)+'px'
                            });
                            video[0].play();
                            video.removeClass('stop');
                            video.next().addClass('hidden');
                            $('.normalslidesjs-stop').click();

                            var videoTimer = setInterval(function(){
                                if(video[0].paused || video[0].ended){
                                    video.next().removeClass('hidden');
                                    $('.normalslidesjs-play').click();
                                    clearInterval(videoTimer);
                                }
                            },1000);
                        }else if(!ifMobile()){
                            video[0].pause();
                            video.addClass('stop');
                            video.next().removeClass('hidden');
                            $('.normalslidesjs-play').click();
                        }
                        e.stopPropagation();
                    });
                    video.on('click',function(e){
                        $(this)[0].play();
                        e.stopPropagation();
                    });
                    video.next().on('click',function(e){
                        video[0].play();
                        e.stopPropagation();
                    });
                }
                //top相册
                var photos = res.albumsList;
                var length = photos.length>10?10:photos.length;
                for(var i = 0; i < length ; i ++){
                    var photo = photos[i];
                    var span = $('<span>').attr('src',photo.original+imgSize.thumbnail).attr('bigsrc',photo.original+imgSize.big)
                        .css({
                            background: 'url('+photo.original+imgSize.thumbnail+') no-repeat center center',
                            backgroundSize: 'cover'
                        }).appendTo(photoDiv);
                }
                //其他家庭信息
                $('#fmlFaceFirst').attr('src',res.face).attr('alt',res.name);
                var shareImg = imgDir+'viptail_logo300.jpg';
                if(res.face){
                    $('#fmlFace').attr('src',res.face).attr('alt',res.name);
                    shareImg = res.face.split('@!')[0]+imgSize.thumbnail;
                }else{
                    $('#fmlFace').attr('src',imgDir+iconImgs.master).attr('alt',res.name);
                }
                $('#fmlName').text(res.name);
                setShareInfo('寄养家庭'+res.name+'的主页',shareImg);
                //评分
                var grade = new Number(res.grade)
                $('#fmlGrade').text(grade.toFixed(1));
                var starDiv = $('#fmlGradeStars');
                crtGrdStrt(res.grade,starDiv);
                //服务列表
                var servers = res.serverList;
                var fosters = servers['寄养服务'];
                if(fosters && fosters.length > 0){
                    $('#fmlFosterP').text('寄养服务').removeClass('hidden');
                    $('#fmlFoster').removeClass('hidden');
                    var fosterUl = $('#fmlFoster').find('ul');
                    crtSrvrLst(fosters,fosterUl);
                }
                var others = servers['其他服务'];
                if(others && others.length > 0){
                    $('#fmlOtherP').text('其他服务').removeClass('hidden');
                    $('#fmlOther').removeClass('hidden');
                    var otherUl = $('#fmlOther').find('ul');
                    crtSrvrLst(others,otherUl);
                }
                //小区环境
                var envs = res.envList;
                var facList = res.facList;
                if(envs.length > 0 || facList.length > 0){
                    var envSection = $('#fmlEnv').removeClass('hidden');
                    $('#fmlEnvP').removeClass('hidden');
                    for(var i = 0; i < envs.length; i ++){
                        var env = envs[i];
                        var img = $('<img>');
                        if(env.icon){
                            img.attr('src',env.icon);
                        }else{
                            img.attr('src','img/'+condImgMap[env.eId]);
                        }
                        var label = $('<label>').text(env.name);
                        $('<span>').append(img,label).appendTo(envSection);
                    }
                    for(var i=0; i<facList.length; i++){
                        var fac = facList[i];
                        var img = $('<img>').addClass('img-responsive').attr('src',fac.icon);
                        var label = $('<label>').text(fac.name);
                        $('<span>').append(img,label).appendTo(envSection);
                    }
                }
                //地址
                if(res.address && res.address.length>0){
                    var address = $('#fmlAddress');
                    address.parent().removeClass('hidden');
                    address.text(res.address);
                    //距离
                    if(res.distance){
                        var dis = parseFloat(res.distance).toFixed(1);
                        dis = dis>100 ? '遥远' : dis+'km';
                        address.next().text(dis);
                    }
                    //查看地图
                    address.parent().on('click',function(){
                        if(res.jd && res.wd){
                            //存在经纬度  可以打开地图查看
                            if(isWechat()){
                                //调用微信查看地图
                                wx.openLocation({
                                    latitude: res.wd,
                                    longitude: res.jd,
                                    name: res.name,
                                    address: res.address,
                                    scale: 13,
                                    infoUrl: ''
                                });
                            }else{
                                location.href = 'map.html?jd='+res.jd+'&wd='+res.wd;
                                setLocalStorage('name',res.name);
                                setLocalStorage('address',res.address);
                            }
                        }else{
                            showMessageAlert('暂无该家庭地图信息');
                        }
                    })
                }
                //家庭简介
                if(res.content && res.content.length>0){
                    var fmlIntro = $('#fmlIntro');
                    fmlIntro.removeClass('hidden');
                    $('#fmlIntroP').removeClass('hidden');
                    var intro = fmlIntro.find('pre');
                    intro.text(res.content);
                    emojifyTo(fmlIntro.find('.emoji_p'));//简介的表情转换
                }
                $('#bottomImg').removeClass('hidden');
                //获取寄养家庭评论列表
                getFmlCommentList(page);
            }else{
                //无该寄养家庭信息
                showMessageAlert(res.respDesc);
            }
            loaded();
            checkBigImg();
        }
    })
}
/**
 * 获取评论列表
 * @type {number}
 */
var page = 1;
var getFmlCommentList = function(page){
    if(page > 1){
        loading();
    }
    var commReqData = {
        ffId: ffId,
        page: page+'',
        pageSize: '15'
    }
    $.ajax({
        url: '/dog2/appFamily/getComments',
        data: paramCoding(commReqData),
        type: 'POST',
        dataType: 'json',
        success: function(res){
            if(res.respCode==0 && res.totalCount>0){
                var commUl = $('#fmlComm');
                //展示评论
                commUl.prev().removeClass('hidden');
                commUl.removeClass('hidden');

                //add comments:
                var more = $('#more').remove();
                var comms = res.results;
                for(var i = 0 ; i < comms.length; i ++){
                    var comm = comms[i];
                    var li = $('<li>'),article = $('<article>');
                    //头像
                    if(comm.face){
                        $('<img>').attr('src',comm.face).addClass('img-circle').appendTo(li);
                    }else{
                        $('<img>').attr('src','img/'+iconImgs.master).addClass('img-circle').appendTo(li);
                    }
                    //用户名 时间 星级
                    $('<h1>').text(comm.uname).appendTo(article);
                    $('<time>').text(timeSettled(comm.createTime)).appendTo(article);
                    var div = $('<div>').addClass('stars').appendTo(article);
                    crtGrdStrt(comm.grade,div);
                    //评论内容
                    $('<pre>').addClass('emoji_p').text(comm.content).appendTo(article);
                    //是否有标签
                    if(comm.tagInfoResults && comm.tagInfoResults.length>0){
                        var tagStr = '';
                        for(var j=0; j<comm.tagInfoResults.length; j++){
                            tagStr += (comm.tagInfoResults[j].tagInfo+'&nbsp&nbsp');
                        }
                        $('<div>').addClass('tags').html(tagStr).appendTo(article);
                    }
                    //标注
                    if(comm.orderDays){
                        var pets = comm.pbList.join('  ');
                        $('<span>').addClass('sub').html(pets+'  '+comm.orderDays+'天').appendTo(article);
                    }
                    //是否有评论回复
                    if(comm.replyContent && comm.replyContent.length>0){
                        var reply = $('<div>').addClass('reply').appendTo(article);
                        $('<span>').addClass('icon').appendTo(reply);//对话框箭头
                        $('<h2>').text('寄养家庭回复').appendTo(reply);
                        $('<time>').text(timeSettled(comm.replyTime)).appendTo(reply);
                        $('<pre>').addClass('emoji_p').text(comm.replyContent).appendTo(reply);
                    }
                    //添加到列表
                    $('<div>').addClass('right').append(article).appendTo(li);
                    li.appendTo(commUl);
                }
                page++;

                //将more添加回底部
                if(comms.length < 15){
                    more.find('a').text('没有更多评论了');
                    more.children('.icon-down').hide();
                }else{
                    more.find('a').text('点击获取更多评论');
                    more.on('click',function(){
                        getFmlCommentList(page);
                    });
                }
                more.appendTo(commUl);
                //表情转换
                emojifyTo($('.emoji_p',commUl));
            }

            if(page > 1){
                loaded();
            }
        }
    })
}
loading();
getFamilyInfo();
$(window).resize(function(){
    var width = getPageWidth();
    $(".pic_list span").each(function(){
        $(this).css({
            height: width*0.235
        });
    });
});
//地图设置
if(isWechat()){
    var wxData = { 'url': location.href };
    $.ajax({
        type: 'POST',
        async: false,
        dataType: 'json',
        url: '/dog2/wechatComm/weChatConfig',
        data: paramCoding(wxData),
        success: function (data) {
            wx.config({
                appId: data.appId,
                timestamp: data.timestamp,
                nonceStr: data.nonceStr,
                signature: data.signature,
                jsApiList: ['getLocation','openLocation']
            });
            if(data.errResult){
                showMessageAlert(data.errMsg,11);
            }
        },
        error: function (data) {
            data = $.parseJSON(data['responseText']);
            showMessageAlert(data['message']);
        },
        cache: false
    });
}
